const { app, BrowserWindow, ipcMain, dialog, Tray, Menu, powerSaveBlocker } = require('electron');
const fs = require('fs').promises;
const path = require('path');
const { spawn } = require('child_process');
const os = require('os');
const AutoLaunch = require('auto-launch');

let mainWindow;
let serverProcess = null;
let isServerRunning = false;
let tray = null;
let powerSaveBlockerId = null;
let windowLoadTimeout = null;
let renderProcessWatchdog = null;

// 获取生产环境下的真实资源路径
function getResourcesPath() {
  if (app.isPackaged) {
    return path.resolve(path.dirname(app.getPath('exe')), 'resources');
  }
  return path.join(__dirname, '../');
}

// 自启动配置
const autoLauncher = new AutoLaunch({
  name: '设备状态监控系统',
  path: app.getPath('exe'),
  isHidden: true
});

// 生产环境自启动配置
if (app.isPackaged) {
  autoLauncher.options = {
    name: '设备状态监控系统',
    path: app.getPath('exe'),
    isHidden: true
  };
}

// 获取服务器执行文件路径
function getServerPath() {
  const serverName = 'server.exe';
  const resourcesPath = getResourcesPath();
  
  // 生产环境路径
  const prodPath = path.join(resourcesPath, serverName);
  
  // 开发环境路径
  const devPath = path.join(__dirname, '../build', serverName);
  
  return app.isPackaged ? prodPath : devPath;
}

// 启动Flask服务器
function startServer() {
  if (isServerRunning) return;
  
  const serverPath = getServerPath();
  console.log(`搜索服务器路径: ${serverPath}`);

  try {
    require('fs').accessSync(serverPath);
    console.log(`启动服务器: ${serverPath}`);
    
    // 设置环境变量
    const env = Object.assign({}, process.env, {
      PATH: `${path.dirname(serverPath)};${process.env.PATH}`
    });

    // Windows特定参数
    const options = { 
      stdio: 'ignore',
      detached: true,
      env: env,
      cwd: path.dirname(serverPath)
    };
    
    serverProcess = spawn(serverPath, [], options);
    serverProcess.unref();
    isServerRunning = true;
    
    serverProcess.on('error', (err) => {
      console.error('服务器启动失败:', err);
      isServerRunning = false;
      dialog.showErrorBox('服务器错误', `服务器启动失败: ${err.message}`);
    });
    
    serverProcess.on('close', (code) => {
      console.log(`服务器进程已退出，代码 ${code}`);
      isServerRunning = false;
      // 自动重启服务器
      if (code !== 0 && app.isReady()) {
        setTimeout(startServer, 5000);
      }
    });
    
    console.log(`服务器已启动，PID: ${serverProcess.pid}`);
    
  } catch (e) {
    console.error(`服务器可执行文件未找到: ${serverPath}`, e);
    dialog.showErrorBox('文件缺失', `服务器文件未找到: ${serverPath}\n请重新安装应用。`);
  }
}

// 改进的进程终止方法
function stopServer() {
  return new Promise((resolve) => {
    if (!isServerRunning || !serverProcess) {
      resolve();
      return;
    }

    console.log(`终止服务器进程 PID: ${serverProcess.pid}`);

    const cleanup = () => {
      isServerRunning = false;
      serverProcess = null;
      resolve();
    };

    if (os.platform() === 'win32') {
      // 使用WMIC确保终止整个进程树
      const wmic = spawn('wmic', [
        'process',
        'where',
        `parentprocessid=${serverProcess.pid}`,
        'delete'
      ]);

      wmic.on('close', (code) => {
        if (code !== 0) {
          // 备用终止方案
          spawn('taskkill', ['/pid', serverProcess.pid, '/f', '/t']);
        }
        cleanup();
      });
    } else {
      serverProcess.kill();
      serverProcess.on('close', cleanup);
    }
  });
}

// 创建系统托盘
function createTray() {
  try {
    // 设置托盘图标，确保路径正确
    const iconPath = app.isPackaged 
      ? path.join(getResourcesPath(), 'assets', '16.ico')
      : path.join(__dirname, '../assets/16.ico');
    
    // 检查图标文件是否存在
    require('fs').accessSync(iconPath);
    tray = new Tray(iconPath);
    
    // 创建托盘上下文菜单
    const contextMenu = Menu.buildFromTemplate([
      {
        label: '显示窗口',
        click: () => {
          if (mainWindow) {
            mainWindow.show();
          } else {
            createWindow();
          }
        }
      },
      {
        label: '重启应用',
        click: async () => {
          await stopServer();
          if (powerSaveBlockerId) {
            powerSaveBlocker.stop(powerSaveBlockerId);
          }
          app.relaunch();
          app.exit(0);
        }
      },
      {
        label: '退出',
        click: async () => {
          await stopServer();
          if (powerSaveBlockerId) {
            powerSaveBlocker.stop(powerSaveBlockerId);
          }
          app.exit(0);
        }
      }
    ]);
    
    // 设置托盘悬停提示
    tray.setToolTip('设备状态监控系统正在运行');
    
    // 设置托盘菜单
    tray.setContextMenu(contextMenu);
    
    // 双击托盘图标显示窗口
    tray.on('double-click', () => {
      if (mainWindow) {
        mainWindow.show();
      } else {
        createWindow();
      }
    });
  } catch (e) {
    console.error('创建托盘失败:', e);
    dialog.showErrorBox('托盘错误', `无法创建系统托盘: ${e.message}`);
  }
}

// 窗口创建 - 添加自动播放权限设置
function createWindow() {
  // 清除之前的超时
  if (windowLoadTimeout) {
    clearTimeout(windowLoadTimeout);
  }
  
  // 销毁已存在的窗口
  if (mainWindow) {
    mainWindow.destroy();
  }

  mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    icon: path.join(__dirname, '../assets/16.ico'),
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      contextIsolation: true,
      nodeIntegration: false,
      autoplayPolicy: 'no-user-gesture-required',
      disableHardwareAcceleration: false,
      backgroundThrottling: false,
      webgl: true,
      webSecurity: true
    },
    show: false // 先不显示窗口，等加载完成再显示
  });

  // 防止窗口被关闭，改为最小化到托盘
  mainWindow.on('close', (event) => {
    if (!app.isQuitting) {
      event.preventDefault();
      mainWindow.hide();
    }
    return false;
  });

  // 页面加载超时处理（防止白屏）
  windowLoadTimeout = setTimeout(() => {
    console.warn('页面加载超时，尝试重新加载');
    if (mainWindow && !mainWindow.isDestroyed()) {
      mainWindow.reload();
      
      // 再次超时则显示错误
      setTimeout(() => {
        if (mainWindow && !mainWindow.isDestroyed() && !mainWindow.isVisible()) {
          dialog.showErrorBox('加载超时', '页面加载超时，应用可能需要重启。');
        }
      }, 15000);
    }
  }, 30000); // 30秒超时

  // 页面加载完成后显示窗口
  mainWindow.webContents.on('did-finish-load', () => {
    clearTimeout(windowLoadTimeout);
    mainWindow.show();
  });

  // 处理页面崩溃
  mainWindow.webContents.on('crashed', (event, killed) => {
    console.error(`页面崩溃，killed: ${killed}`);
    dialog.showErrorBox('页面崩溃', '应用界面已崩溃，将尝试重新加载。');
    if (!mainWindow.isDestroyed()) {
      mainWindow.reload();
    }
  });

  // 处理渲染进程无响应
  mainWindow.webContents.on('unresponsive', () => {
    console.error('页面无响应');
    dialog.showMessageBox(mainWindow, {
      type: 'warning',
      title: '页面无响应',
      message: '应用界面无响应，是否重新加载？',
      buttons: ['重新加载', '取消']
    }).then(result => {
      if (result.response === 0 && !mainWindow.isDestroyed()) {
        mainWindow.reload();
      }
    });
  });

  // 处理GPU进程崩溃
  mainWindow.on('gpu-process-crashed', (event, killed) => {
    console.error(`GPU进程崩溃，killed: ${killed}`);
    dialog.showErrorBox('GPU进程崩溃', '图形处理进程已崩溃，应用将尝试继续运行。');
  });

  // 加载页面
  mainWindow.loadFile(path.join(__dirname, 'index.html'))
    .catch(err => {
      console.error('加载页面失败:', err);
      dialog.showErrorBox('加载失败', `无法加载应用界面: ${err.message}`);
    });

  // 开发环境下打开调试工具
  if (!app.isPackaged) {
    mainWindow.webContents.openDevTools();
  }

  // 设置渲染进程监控
  setupRenderProcessWatchdog();
}

// 设置渲染进程监控
function setupRenderProcessWatchdog() {
  // 清除之前的监控
  if (renderProcessWatchdog) {
    clearInterval(renderProcessWatchdog);
  }

  // 每分钟检查一次渲染进程状态
  renderProcessWatchdog = setInterval(() => {
    if (mainWindow && !mainWindow.isDestroyed()) {
      // 发送心跳检测
      try {
        mainWindow.webContents.send('heartbeat', Date.now());
      } catch (err) {
        console.error('发送心跳失败，可能渲染进程已崩溃:', err);
        if (!mainWindow.isDestroyed()) {
          mainWindow.reload();
        }
      }
    } else {
      clearInterval(renderProcessWatchdog);
    }
  }, 60000);
}

// 阻止系统进入节能模式
function preventSystemSleep() {
  // 停止已有的阻止
  if (powerSaveBlockerId) {
    powerSaveBlocker.stop(powerSaveBlockerId);
  }
  // 阻止系统进入睡眠和显示器关闭
  powerSaveBlockerId = powerSaveBlocker.start('prevent-display-sleep');
  console.log('已阻止系统进入节能模式，ID:', powerSaveBlockerId);
}

// IPC通信处理
ipcMain.handle('auto-launch:get-status', () => autoLauncher.isEnabled());
ipcMain.handle('auto-launch:toggle', (_, enabled) => 
  enabled ? autoLauncher.enable() : autoLauncher.disable()
);
ipcMain.handle('dialog:openFile', async () => {
  try {
    const { filePaths } = await dialog.showOpenDialog({
      properties: ['openFile'],
      filters: [
        { name: '配置文件', extensions: ['ini', 'txt','conf', 'cfg', 'json', 'yaml', 'yml'] },
        { name: '所有文件', extensions: ['*'] }
      ]
    });
    // 确保返回单个文件路径字符串
    return filePaths && filePaths.length ? filePaths[0] : '';
  } catch (err) {
    console.error('打开文件对话框失败:', err);
    throw err;
  }
});
ipcMain.handle('dialog:showSaveDialog', async () => {
  try {
    const { filePath } = await dialog.showSaveDialog({
      filters: [
        { name: '配置文件', extensions: ['ini','txt', 'conf', 'cfg', 'json', 'yaml', 'yml'] },
        { name: '所有文件', extensions: ['*'] }
      ]
    });
    return filePath;
  } catch (err) {
    console.error('保存文件对话框失败:', err);
    throw err;
  }
});
ipcMain.handle('fs:readFile', async (_, filePath) => {
  try {
    const content = await fs.readFile(filePath, 'utf-8');
    const lines = content.split('\n');
    
    // 只提取包含lims_url=的行，并移除前缀
    const limsUrlLines = lines
      .filter(line => line.includes('lims_url='))
      .map(line => line.replace('lims_url=', ''));
      
    return limsUrlLines.join('\n');
  } catch (error) {
    console.error('读取文件失败:', error);
    throw error;
  }
});

ipcMain.handle('fs:writeFile', async (_, filePath, content) => {
  try {
    // 先读取原始文件内容
    const originalContent = await fs.readFile(filePath, 'utf-8');
    const originalLines = originalContent.split('\n');
    
    // 分离原始文件中的非lims_url行（需要保留的内容）
    const nonLimsLines = originalLines.filter(line => !line.includes('lims_url='));
    
    // 处理用户输入的内容，添加lims_url=前缀
    const userLines = content.split('\n')
      .filter(line => line.trim() !== '') // 过滤空行
      .map(line => `lims_url=${line}`); // 添加前缀
      
    // 合并内容：原始非lims行 + 新的lims行
    const newContent = [...nonLimsLines, ...userLines].join('\n');
    
    await fs.writeFile(filePath, newContent, 'utf-8');
    return true;
  } catch (error) {
    console.error('写入文件失败:', error);
    throw error;
  }
});

// 处理语音合成权限请求
ipcMain.handle('speech:request-permission', async () => {
  if (mainWindow && !mainWindow.isDestroyed()) {
    try {
      return await mainWindow.webContents.executeJavaScript(`
        (() => {
          return new Promise((resolve) => {
            const synth = window.speechSynthesis;
            if (synth) {
              const utterance = new SpeechSynthesisUtterance('');
              synth.speak(utterance);
              setTimeout(() => {
                synth.cancel();
                resolve(true);
              }, 100);
            } else {
              resolve(false);
            }
          });
        })()
      `);
    } catch (err) {
      console.error('语音权限请求失败:', err);
      return false;
    }
  }
  return false;
});

// 应用生命周期
app.whenReady().then(() => {
  // 提高应用稳定性的设置
  app.commandLine.appendSwitch('disable-gpu-program-cache');
  app.commandLine.appendSwitch('disable-software-rasterizer');
  app.commandLine.appendSwitch('enable-features', 'VaapiVideoDecoder');
  
  // 设置应用ID，有助于Windows识别为后台任务
  if (os.platform() === 'win32') {
    app.setAppUserModelId('com.example.devicemonitor');
  }
  
  autoLauncher.isEnabled()
    .then(enabled => console.log(`开机自启动: ${enabled}`))
    .catch(console.error);
  
  // 创建系统托盘
  createTray();
  
  // 阻止系统进入节能模式
  preventSystemSleep();
  
  startServer();
  createWindow();
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  } else {
    mainWindow.show();
  }
});

// 退出处理
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    // 保持后台运行
  }
});

// 改进的退出序列
app.on('before-quit', async (event) => {
  app.isQuitting = true;
  
  event.preventDefault();
  console.log('正在终止服务器进程...');
  await stopServer();
  
  // 停止阻止系统节能
  if (powerSaveBlockerId) {
    powerSaveBlocker.stop(powerSaveBlockerId);
  }
  
  // 清除定时器
  if (renderProcessWatchdog) {
    clearInterval(renderProcessWatchdog);
  }
  
  console.log('服务器进程已结束');
  app.exit(0);
});

// 捕获未处理的异常，防止应用崩溃
process.on('uncaughtException', (error) => {
  console.error('未捕获的异常:', error);
  dialog.showErrorBox('应用错误', `发生未预期的错误: ${error.message}\n应用将尝试继续运行。`);
});

process.on('unhandledRejection', (reason, promise) => {
  console.error('未处理的Promise拒绝:', reason);
  dialog.showErrorBox('异步操作错误', `发生错误: ${reason.message || reason}\n应用将尝试继续运行。`);
});
    